
//
// 121231 - AH - Created.
//

package org.japril.swing.jutil.logging;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JEditorPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;

import org.japril.jutil.ComposedText;
import org.japril.jutil.logging.LogSink;

/**
 * <p>
 *   Panel and
 *   {@link LogSink} that format log in HTML.
 * </p>
 * @author Arne Halvorsen (AH)
 */
@SuppressWarnings("serial")
public final class HtmlLogPanel extends JPanel implements LogSink
{
  private final JEditorPane m_log=new JEditorPane("text/html", null);
  
  private final ComposedText m_ct=new ComposedText(3);
  
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public HtmlLogPanel()
  {
    m_ct.println("<html><body>");
    m_ct.println(2, "</body></html>");
    
    setLayout(new BorderLayout());
    
    m_log.setEditable(false);
    add(new JScrollPane(m_log));
    
    makeToolBar();
  }
  
  private void makeToolBar()
  {
    JToolBar bar=new JToolBar();
    bar.add(m_clearAction);
    add(bar, BorderLayout.NORTH);
  }
  
  private final Action m_clearAction=new AbstractAction("Clear")
  {  
    public void actionPerformed(ActionEvent e){ clear(); }
  };
  
  public void clear(){ m_ct.clear(1); m_log.setText(""); }
  
  private Class<?> m_currClass=null;
  
  private String m_currMethod=null;
  
  // Specified in LogSink.
  public void log(Class<?> clazz, String method, String msg)
  {
    if (clazz!=null)
    {
      if (clazz!=m_currClass)
      {
        String name=clazz.getName();
        m_ct.println(1, "<h2>"+name+"</h2>");
      }
      m_currClass=clazz;
    }
    
    if (method!=null)
    {
      if (!method.equals(m_currMethod))
      {
        m_ct.println(1, "<h3>"+method+"</h3>");
      }
      m_currMethod=method;
    }
    
    m_ct.println(1, msg);
    
    m_log.setText(m_ct.toString());
  }

  // Specified in LogSink.
  public void rlog(Class<?> clazz, String method, String msg)
  {
    m_ct.println(1, msg);
    m_log.setText(m_ct.toString());
  }
  
}
